﻿#include "CameraFactory.h"
#include "CameraTUCAM.h"
#include "CameraTUCAM_private.h"
namespace Qly{

QList<IndustryCameraInfo> CameraFactory::availableCameras()
{
    return availableCameras(CameraType::TOUP_USB);;
}

IndustryCamera *CameraFactory::findCameraByName(QString name, QObject *parent)
{
    Qly::CameraTUCAM * p = new Qly::CameraTUCAM(parent);
    if(!p->openCameraByID(name))
    {
        delete p;
        p =nullptr;
    }
    return p;
}

IndustryCamera *CameraFactory::defaultCamera(QObject *parent)
{
    Qly::CameraTUCAM * p = new Qly::CameraTUCAM(parent);
    if(!p->openDefaultCamera())
    {
        delete p;
        p =nullptr;
    }
    return p;
}

QString CameraFactory::vendorName()
{
    return QString("TUSCEN");
}

static TUCAM_INIT m_itApi;       // SDK API initialized object
CameraFactory::CameraFactory()
{
    TUCAM_Api_Init(&m_itApi);
}

QList<IndustryCameraInfo> CameraFactory::availableCameras(QSet<CameraType> types)
{
    if( types.contains(CameraType::TOUP_USB) )
    {
        return availableCameras(CameraType::TOUP_USB);
    }
    return QList<IndustryCameraInfo>();
}


QList<IndustryCameraInfo> CameraFactory::availableCameras(CameraType type)
{
    QList<Qly::IndustryCameraInfo> list;
    if(type != CameraType::TUCAM_USB)
    {
        return list;
    }
    unsigned cnt = getAutoInitInstance()->cameraCount();
    for(unsigned index = 0; index < cnt; index++)
    {
        Qly::IndustryCameraInfo info;
        TUCAM_OPEN opCam;
        opCam.uiIdxOpen = index;
        TUCAM_Dev_Open(&opCam);
        TUCAM_VALUE_INFO valInfo;
        valInfo.nID = TUIDI_CAMERA_MODEL;
        TUCAM_Dev_GetInfo(opCam.hIdxTUCam, &valInfo);
        info.modelName = QString(valInfo.pText);

        char cSN[TUSN_SIZE] = {0};
        TUCAM_REG_RW regRW;
        regRW.nRegType = TUREG_SN;
        regRW.pBuf = &cSN[0];
        regRW.nBufSize = TUSN_SIZE;
        if (TUCAMRET_SUCCESS == TUCAM_Reg_Read(opCam.hIdxTUCam, regRW))
        {
            info.cameraID = QString(regRW.pBuf);
        }

        valInfo.nID = TUIDI_CAMERA_MODEL;
        TUCAM_Dev_GetInfo(opCam.hIdxTUCam, &valInfo);
        info.description = QString(valInfo.pText);
        info.type = Qly::CameraType::TUCAM_USB;

        TUCAM_Dev_Close(opCam.hIdxTUCam);
        list << info;
    }

    return list;
}
bool Qly::CameraFactory::release(IndustryCamera *camera)
{
    Qly::CameraTUCAM * pCamera = dynamic_cast<Qly::CameraTUCAM *> (camera); // 能够转换成功说明是这个dll new出来的对象。可以删除。
    if(pCamera)
    {
        delete pCamera;
        return true;
    }
    return false; //说明不能删除这个对象
}
} //namespace Qly

Qly::CameraFactoryInterface *CreateInstance()
{

    Qly::CameraFactory * cameraFactory = new Qly::CameraFactory();
    return cameraFactory;
}

void Release(Qly::CameraFactoryInterface *p)
{
    delete p;
}
